package com.jy.adscm.hcPlan.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.hcPlan.bean.HcPlanMakePartMateriel;
import com.jy.adscm.hcPlan.bean.HcPlanMakePartMaterielExample;
import com.jy.adscm.hcPlan.bean.HcPlanMaterielPrice;
import com.jy.adscm.hcPlan.mapper.mysql.HcPlanMakePartMaterielExampleMapper;
import com.jy.adscm.hcPlan.mapper.mysql.HcPlanMakePartMaterielMapper;
import com.jy.adscm.hcPlan.mapper.mysql.HcPlanMaterielPriceMapper;
import com.jy.adscm.hcPlan.service.HcPlanMaterielPriceService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 物料采购财务报表 服务实现类
 * </p>
 *
 * @author yyy
 * @since 2018-08-24
 */
@Service
public class HcPlanMaterielPriceServiceImpl extends ServiceImpl<HcPlanMaterielPriceMapper, HcPlanMaterielPrice> implements HcPlanMaterielPriceService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HcPlanMaterielPriceMapper hcPlanMaterielPriceMapper;
    @Autowired
    HcPlanMakePartMaterielMapper hcPlanMakePartMaterielMapper;
    @Autowired
    HcPlanMakePartMaterielExampleMapper hcPlanMakePartMaterielExampleMapper;


    @Override
    public void loadMaterielPrice(String merge_id)  throws AdscmSystemException {

        logger.info("开始构造【"+merge_id+"】的财务数据...");

        try{
//            Page<HcPlanMakePartMaterielExample> page = new Page<HcPlanMakePartMaterielExample>();
//            page.setCurrent(1);
//            page.setSize(1);
//            page.setSearchCount(true);//查询总记录数
            Wrapper<HcPlanMakePartMaterielExample> wrapper = new EntityWrapper<>();
            wrapper.eq("merge_puchase_id",merge_id);

            List<HcPlanMakePartMaterielExample> exampleList = hcPlanMakePartMaterielExampleMapper.selectList(wrapper);

            if (exampleList != null && exampleList.size()>0){
                HcPlanMakePartMaterielExample example = exampleList.get(0);

                HcPlanMaterielPrice price = new HcPlanMaterielPrice();
                price.setMerge_id(merge_id);

                HcPlanMaterielPrice price_1 = hcPlanMaterielPriceMapper.selectOne(price);

                boolean isUpdate = false;
                if (AdscmBaseUtils.getInstance().isNotEmpty(price_1,"id")){
                    //更新
                    isUpdate = true;
                    price = price_1;
                }

//                HcPlanMakePartMateriel materiel = hcPlanMakePartMaterielMapper.selectById(example.getMake_materiel_id());
                Double consumePrice = example.getMateriel_total_price();

                Double pp = exampleList.size() * consumePrice;

                price.setMateriel_name(example.getMake_materiel_name());
                price.setMerge_num(exampleList.size());
                price.setAudit_pass(0);
                price.setPuchase_price(example.getMateriel_total_price().floatValue());
                price.setMateriel_purchase_time(example.getMateriel_purchase_time());
                price.setSupplier_id(example.getSupplier_id());
                price.setSupplier_name(example.getSupplier_name());
                price.setPayment_date(example.getPayment_date());//付款时间


                if (isUpdate){
                    hcPlanMaterielPriceMapper.updateById(price);
                }else {
                    hcPlanMaterielPriceMapper.insert(price);
                }


            }




        }catch (Exception e){
            logger.error("构造【"+merge_id+"】的财务数据异常",e);
            throw new AdscmSystemException(e.getMessage());
        }

    }


    @Override
    public Map<String, Object> getTheWeekPlanPrice(String merge_id) throws AdscmSystemException {

        logger.info("根据并单ID【"+merge_id+"】，获取这个采购日期所在的周的预计消费金额...");
        try{
            Map<String, Object> map = new HashMap<>();
            HcPlanMaterielPrice price = new HcPlanMaterielPrice();
            price.setMerge_id(merge_id);

            price = hcPlanMaterielPriceMapper.selectOne(price);

            if (AdscmBaseUtils.getInstance().isNotEmpty(price,"id")){
                Map<String, Object> weekByDate = AdscmDateUtils.getWeekByDate(price.getMateriel_purchase_time());
                map.put("whereWeek",AdscmDateUtils.getTheYear(price.getMateriel_purchase_time())+":"+weekByDate.get("whereWeek"));
                map.put("theWeekPrice",price.getPuchase_price());

                String beginDate = (String)weekByDate.get("benginDate");
                String endDate = (String)weekByDate.get("endDate");
                Double allPrice = hcPlanMaterielPriceMapper.getAllPriceByDate(beginDate, endDate);

                if (allPrice == null){
                    allPrice = 0D;
                }

                map.put("theWeekOtherPrice",allPrice);

            }else {
                throw new AdscmSystemException("没有找到这个财务清单...");
            }
            return map;
        }catch (Exception e){
            logger.error("根据并单ID【"+merge_id+"】，获取这个采购日期所在的周的预计消费金额异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }


    @Override
    public List<Map<String, Object>> getTheWeekPlanPrice(String[] mergeIds) throws AdscmSystemException {
        logger.info("根据并单ID集合，获取这个采购日期所在的周的预计消费金额...");
        try{
            List<Map<String, Object>> list = new ArrayList<>();

            List<HcPlanMaterielPrice> prices = null;
            if (mergeIds != null && mergeIds.length>0){
                prices = hcPlanMaterielPriceMapper.getMaterielPricesByMergeIds(Arrays.asList(mergeIds));
                if (prices != null && prices.size()>0){
                    for (HcPlanMaterielPrice price :
                            prices) {
                        Map<String, Object> map = new HashMap<>();
                        if (AdscmBaseUtils.getInstance().isNotEmpty(price,"id")){
                            Map<String, Object> weekByDate = AdscmDateUtils.getWeekByDate(price.getMateriel_purchase_time());
                            map.put("whereWeek",AdscmDateUtils.getTheYear(price.getMateriel_purchase_time())+":"+weekByDate.get("whereWeek"));
                            map.put("theWeekPrice",price.getPuchase_price());

                            String beginDate = (String)weekByDate.get("benginDate");
                            String endDate = (String)weekByDate.get("endDate");
                            Double allPrice = hcPlanMaterielPriceMapper.getAllPriceByDate(beginDate, endDate);

                            if (allPrice == null){
                                allPrice = 0D;
                            }

                            map.put("theWeekOtherPrice",allPrice);
                            map.put("mergerId",price.getMerge_id());
                            list.add(map);
                        }

                    }
                }
            }else {
                throw new AdscmSystemException("没有获取到参数并单ID集合...");
            }

            return list;
        }catch (Exception e){
            logger.error("根据并单ID集合，获取这个采购日期所在的周的预计消费金额异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Transactional
    @Override
    public void submitAudit(String[] mergeIds, Integer audit_status) throws AdscmSystemException {
        logger.info("提交财务报表审核...");
        try{
            List<HcPlanMaterielPrice> prices = null;
            if (mergeIds != null && mergeIds.length>0) {
                prices = hcPlanMaterielPriceMapper.getMaterielPricesByMergeIds(Arrays.asList(mergeIds));
                if (prices != null && prices.size()>0){
                    for (HcPlanMaterielPrice price :
                            prices) {
                        price.setAudit_pass(audit_status);
                        hcPlanMaterielPriceMapper.updateById(price);

                        //修改物料那边的任务状态为 3 ：财务审核通过的状态 为 1
                        if (audit_status == 1){
                            Wrapper<HcPlanMakePartMaterielExample> wrapper = new EntityWrapper<>();
                            wrapper.eq("merge_puchase_id",price.getMerge_id());
                            List<HcPlanMakePartMaterielExample> materielExamples = hcPlanMakePartMaterielExampleMapper.selectList(wrapper);
                            if (materielExamples != null && materielExamples.size()>0){
                                for (HcPlanMakePartMaterielExample example :
                                        materielExamples) {
                                    example.setPart_materiel_status(3);
                                    hcPlanMakePartMaterielExampleMapper.updateById(example);
                                }
                            }
                        }


                    }
                }


            }

        }catch (Exception e){
            logger.error("提交财务报表审核异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }
}
